<template>
  <div id="category">
    <el-button type="danger" @click="addFirst({type: 'addFirstCategory'})">添加一级分类</el-button>
    <div class="hr_e9e9e9"></div>
    <el-row :gutter="30">
      <el-col :span="8">
        <div class="category_wrap">
          <div
            class="category"
            v-for="item in data.categoryData"
            :key="item.id"
          >
            <h4>
              <svg-icon icon-class="open"></svg-icon>
              {{ item.category_name }}
              <div class="button_group">
                <el-button
                  type="danger"
                  round
                  size="mini"
                  @click="editCategory({data: item, type: 'editFirstCategory' })"
                >编辑
                </el-button>
                <el-button
                  type="success"
                  round
                  size="mini"
                  @click="handleAddChildren({data: item, type: 'addChildrenCategory' })"
                >添加子级
                </el-button>
                <el-button
                  round
                  size="mini"
                  @click="deleteCategoryConfirm(item.id)"
                >删除
                </el-button>
              </div>
            </h4>
            <ul v-if="item.children">
              <li
                v-for="childrenItem in item.children"
                :key="childrenItem.id"
              >
                {{ childrenItem.category_name }}
                <div class="button_group">
                  <el-button
                    type="danger"
                    round
                    size="mini"
                    @click="hanldeEditChildrenCategory({data: childrenItem, type: 'editChildrenCategory' })"
                  >编辑
                  </el-button>
                  <el-button
                    round
                    size="mini"
                    @click="deleteCategoryConfirm(childrenItem.id)"
                  >删除
                  </el-button>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </el-col>
      <el-col :span="16">
        <h4 class="menu_title">一级分类编辑</h4>
        <el-form
          label-position="left"
          label-width="130px"
          :model="data.addForm"
          ref="addForm"
          class="form_wrap"
        >
          <el-form-item
            prop="categoryName"
            label="一级分类名称："
            v-if="data.categoryStaus === '' || data.categoryStaus === 'firstClass' "
          >
            <el-input v-model="data.addForm.categoryName" :disabled="data.categoryNameDisabled"></el-input>
          </el-form-item>
          <el-form-item
            prop="setCategoryName"
            label="二级分类名称："
            v-if="data.categoryStaus === '' || data.categoryStaus !== 'firstClass' "

          >
            <el-input v-model="data.addForm.setCategoryName" :disabled="data.setCategoryNameDisabled"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="danger"
              @click="submitForm"
              :loading="data.subLoading"
              :disabled="data.subDisabled"
            >确定
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { GetCategory, AddFirstCategory, AddChildrenCategory, DelectCategory, EditFirstCategory } from "@/api/news";
import { global } from "@/utils/global3.0";
import { reactive, ref, onMounted } from "@vue/composition-api";

export default {
  name: "category",
  setup(props, { root, refs }) {
    // global方法
    const { confirm } = global();

    // data
    const data = reactive({
      categoryStaus: "",
      delectID: "", // 删除
      subLoading: false,
      categoryNameDisabled: true,
      setCategoryNameDisabled: true,
      subDisabled: true,
      // 提交类型
      subType: "",
      addForm: {
        categoryName: "",
        setCategoryName: ""
      },
      categoryData: [],
      current: []
    });

    /**
     * methods
     */
      // 获取分类
    const getCategoryData = () => {
        root.$store.dispatch("common/getInfoCategoryAll", "").then(res => {
          data.categoryData = res;
        });
      };

    // 删除分类
    const deleteCategoryConfirm = (ID) => {
      data.delectID = ID;
      confirm({
        message: "是否删除当前分类，确认后无法恢复！",
        success: deleteCategory,
        fail: () => {
          data.delectID = 0;
        }
      });
    };
    const deleteCategory = () => {
      DelectCategory({ categoryId: data.delectID || 0 }).then(res => {
        let data = res.data;
        /**
         * 操作数组
         * 第一种方法 findIndex() es6
         */
        // let index = getCategoryData.data.findIndex(item => item.id == data.delectID);
        // 删除数组指定数据
        // getCategoryData.data.split(index, 1);
        /**
         * 第二种方法 filter() es6
         */
        // let newData = categoryData.data.filter(item => item.id !== data.delectID);
        // categoryData.data = newData;
        /**
         * 第三种方法 刷新接口
         */
        getCategoryData();

        if (data.resCode === 0) {
          root.$message.success(data.message);
        }

      }).catch(error => {
        console.log(error);
      });
    };

    // 编辑一级分类
    const editCategory = (params) => {
      data.categoryStaus = "firstClass";
      data.categoryNameDisabled = false;
      data.subDisabled = false;
      // 一级名称输入还原名称
      data.addForm.categoryName = params.data.category_name;
      data.subType = params.type;
      // 存储当前数据对象
      data.current = params.data;
    };
    // 请求编辑一级分类的接口
    const editFirstCategory = (params) => {
      data.subLoading = true;
      if (data.current.length == 0) {
        root.$message.error("未选择分类");
        data.subLoading = false;
        return false;
      }
      let requestData = {
        id: data.current.id,
        categoryName: data.addForm.categoryName
      };
      // 编辑分类
      EditFirstCategory(requestData).then(res => {
        let resData = res.data;
        if (resData.resCode === 0) {
          root.$message.success(resData.message);
        }
        data.current.category_name = resData.data.data.categoryName;
        restForm();
        // 清空
        data.current = [];
      }).catch(error => {
        restForm();
        console.log(error);
      });
    };

    // 编辑子级分类
    const hanldeEditChildrenCategory = (params) => {
      // 显示二级输入框
      data.categoryStaus = "1";
      data.subType = params.type;
      // 禁用一级输入框
      data.categoryNameDisabled = true;
      // 显示二级输入框
      data.setCategoryNameDisabled = false;
      // 启用确定按钮
      data.subDisabled = false;
      // 存储数据
      data.current = params.data;
      // 显示子级分类文本
      data.addForm.setCategoryName = params.data.category_name;
    };
    // 编辑子级分类请求接口
    const editChildrenCategory = (params) => {
      data.subLoading = true;
      if (data.current.length == 0) {
        root.$message.error("未选择分类");
        data.subLoading = false;
        return false;
      }
      let requestData = {
        id: data.current.id,
        categoryName: data.addForm.setCategoryName
      };
      // 编辑分类
      EditFirstCategory(requestData).then(res => {
        let resData = res.data;
        if (resData.resCode === 0) {
          root.$message.success(resData.message);
        }
        getCategoryData();
        restForm();
        // 清空
        data.current = [];
      }).catch(error => {
        restForm();
        console.log(error);
      });
    };


    // 添加一级分类
    const addFirst = (params) => {
      data.subType = params.type;
      data.categoryStaus = "firstClass";
      data.categoryNameDisabled = false;
      data.subDisabled = false;
    };
    // 请求添加一级分类的接口
    const addFirstCategory = () => {
      if (!data.addForm.categoryName) {
        root.$message.warning("分类名称不能为空");
        return false;
      }
      data.subLoading = true;
      AddFirstCategory({ categoryName: data.addForm.categoryName }).then(res => {
        let resData = res.data;
        if (resData.resCode === 0) {
          root.$message.success(resData.message);
          /**
           *  把新增的数据添加到分类 两种处理方式
           *  1. 请求接口 缺点：浪费资源
           *  2. 直接push, 请求接口后返回的数据
           */
          data.categoryData.push(resData.data);
        }
        restForm();
      }).catch(error => {
        restForm();
        console.log(error);
      });
    };
    // 添加子级分类
    const handleAddChildren = (params) => {
      // 显示二级输入框
      data.categoryStaus = "";
      data.subType = params.type;
      // 禁用一级输入框
      data.categoryNameDisabled = true;
      // 显示二级输入框
      data.setCategoryNameDisabled = false;
      // 启用确定按钮
      data.subDisabled = false;
      // 存储数据
      data.current = params.data;
      // 显示一级分类文本
      data.addForm.categoryName = params.data.category_name;
    };

    // 请求添加子级分类的接口
    const addChildrenCategory = () => {
      if (!data.addForm.setCategoryName) {
        root.$message.warning("分类名称不能为空");
        return false;
      }
      let requestData = {
        parentId: data.current.id,
        categoryName: data.addForm.setCategoryName
      };
      data.subLoading = true;
      AddChildrenCategory(requestData).then(res => {
        let resData = res.data;
        if (resData.resCode === 0) {
          root.$message.success(resData.message);
          // 更新分类
          getCategoryData();
          // 显示二级输入框
          data.setCategoryNameDisabled = true;
          // 启用确定按钮
          data.subDisabled = true;
        }
        restForm();
      }).catch(error => {
        restForm();
        console.log(error);
      });
    };

    // 提交
    const submitForm = () => {
      if (data.subType === "addFirstCategory") {
        addFirstCategory();
      }
      if (data.subType === "editFirstCategory") {
        editFirstCategory();
      }
      if (data.subType === "addChildrenCategory") {
        addChildrenCategory();
      }
      if (data.subType === "editChildrenCategory") {
        editChildrenCategory();
      }
    };

    // 清除表单状态
    const restForm = () => {
      data.subLoading = false;
      refs["addForm"].resetFields();
    };
    /**
     * 生命周期
     */
    // 挂载完成时执行，（页面DOM元素完成时，实例完成）
    onMounted(() => {
      getCategoryData();
    });
    return {
      // reactive
      data,
      // methods
      addFirst,
      handleAddChildren,
      deleteCategoryConfirm,
      deleteCategory,
      editCategory,
      hanldeEditChildrenCategory,
      submitForm
    };
  }
};
</script>

<style lang="scss" scoped>
@import "../../styles/config.scss";

.hr_e9e9e9 {
  margin: 30px -30px;
  background-color: #e9e9e9;
  height: 1px;
}

.category_wrap {
  div:first-child {
    &:before {
      top: 20px;
    }
  }

  div:last-child {
    &:before {
      bottom: 21px;
    }
  }
}

.menu_title {
  padding-left: 22px;
  background-color: #f3f3f3;
  line-height: 44px;
}

.category {
  position: relative;
  line-height: 44px;
  cursor: pointer;

  &:before {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 22px;
    width: 32px;
    border-left: 1px dotted #000;
  }

  h4 {
    position: relative;
    padding-left: 40px;
  }

  svg {
    position: absolute;
    left: 15px;
    top: 15px;
    background-color: #fff;
    font-size: 17px;
  }

  li {
    position: relative;
    padding-left: 37px;
    margin-left: 23px;

    &:before {
      content: "";
      position: absolute;
      top: 22px;
      left: 0;
      width: 32px;
      border-bottom: 1px dotted #000;
    }
  }

  li, h4 {
    @include webkit(transition, all .5s ease 0s);

    &:hover {
      background-color: #f3f3f3;

      .button_group {
        display: block;
      }
    }
  }
}

.button_group {
  display: none;
  position: absolute;
  z-index: 2;
  right: 12px;
  top: -1px;

  button {
    font-size: 12px;
  }
}

.form_wrap {
  width: 410px;
  margin-top: 26px;
}
</style>
